<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Constants\CrowSendingConstants;
use App\CustHub\Constants\FrdCircTaskStatusConstants;
use App\CustHub\Constants\TaskTypeConstants;
use App\CustHub\Model\ChFriendCircleTask;
use Carbon\Carbon;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Config\Annotation\Value;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;
use function Hyperf\Collection\data_get;

class ChFriendCircleTaskMapper extends AbstractMapper
{
    #[Value('cache.default.prefix')]
    protected string $prefix;


    public function assignModel()
    {
        return $this->model = ChFriendCircleTask::class;
    }

    /**
     * 通过id获取任务信息
     * @param mixed $id
     * @return MineModel|Model|string|Builder|null
     */
//    #[Cacheable(prefix: 'friend_circle_task_info',value: '#{id}',ttl: 15 * 60)]
    public function findById(mixed $id): ChFriendCircleTask|Model|string|Builder|null
    {
        return $this->model::query()->where('id',$id)->first();
    }

    public function delCache(mixed $id)
    {
        $redis = redis();
        $keyOne = $this->prefix . 'friend_circle_task_info:'.$id;
        $redis->del([$keyOne]);
    }

    /**
     * 重置分组
     * @param mixed $groupId
     * @return bool|int
     */
    public function restGroup(mixed $groupId): bool|int
    {
        return $this->model::query()->where('group_id',$groupId)->update([
            'group_id' => 0
        ]);
    }

    public function handleSearch(Builder $query, array $params): Builder
    {
        $corpId = data_get($params, 'corp_id');
        $groupId = data_get($params, 'group_id');
        $userId = data_get($params, 'user_id');
        $keyword = data_get($params, 'keyword');
        $status = data_get($params,'status');
        $date = data_get($params,'date');

        $type = data_get($params,'type');

        if(filled($groupId)){
            $query->where('group_id',$groupId);
        }

        if(!empty($date)){
            $query->whereRaw("DATE(FROM_UNIXTIME(send_time)) = '$date'");
        }

        if(!empty($corpId)){
            $query->where('corp_id',$corpId);
        }

        if(!empty($userId)){
            $query->where('uid',$userId);
        }

        if(!empty($keyword)){
            $query->where('name','like','%'.$keyword.'%');
        }

        if(filled($status)){
            $query->where('status',$status);
        }

        $filterTime = Carbon::now()->subDays(14)->toDateTimeString();
        if($type == 1){
            //查询两周前的数据
            $query->where('created_at','<',$filterTime);
        }elseif(filled($type) && $type == 0){
            //查询近两周的数据
            $query->where('created_at','>=',$filterTime);
        }

        return $query;
    }

    //#[Cacheable(prefix: "friend_circle_task_calendar", value:"#{uid}_#{date}#{status}", ttl:3600)]
    public function getTaskList($uid,$date,$status=null)
    {
        $carbonDate = Carbon::parse($date);
        $dayList = getDatesOfMonth($carbonDate->year,$carbonDate->month);
        $newList=[];
        $where['uid']=$uid;
        if(filled($status)){
            $where['status']=CrowSendingConstants::convertToTaskStatus($status);
        }
        $list=$this->model::query()->where($where)
            ->whereYear(Db::raw('FROM_UNIXTIME(send_time)'), $carbonDate->year) // 检索年份
            ->whereMonth(DB::raw('FROM_UNIXTIME(send_time)'), $carbonDate->month) // 检索月份
            ->select(['id','name as title','status','send_time as start_time'])
            ->get()
            ->toArray();

        foreach ($list as $item) {
            // 获取任务开始日期
            $startDate = datetime($item['start_time'], "Y-m-d");

            // 处理每一项数据
            $item['task_type'] = TaskTypeConstants::FRIEND_CIRCLE;
            $item['start_time'] = datetime($item['start_time']);
            $item['status'] = FrdCircTaskStatusConstants::convertToTaskStatus($item['status']);

            // 将任务按日期归类
            if (in_array($startDate, $dayList)) {
                $newList[$startDate][] = $item;
            }
        }

        return $newList;
    }
}